package com.bsoft.gol.hbs.dao;

import com.bsoft.gol.hbs.bean.qo.HealthActivitiesListQo;
import com.bsoft.gol.hbs.utils.CommonUtils;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.HibernateSupportDelegateDAO;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import hcn.base.healthact.HealthActivities;
import hcn.base.healthact.qo.HealthActivitiesQo;
import hcn.base.healthact.vo.HealthActivitiesAppVO;
import hcn.base.healthact.vo.HealthActivitiesVO;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.model.PageInfo;
import org.atag.dao.model.SimplePageInfo;
import org.hibernate.Query;
import org.hibernate.StatelessSession;

import java.util.List;

public abstract class HealthActivitiesDAO extends HibernateSupportDelegateDAO<HealthActivities> {

    public HealthActivitiesDAO() {
        this.setKeyField("id");
    }


    public HealthActivitiesAppVO getPcnHealthActivities(final HealthActivitiesQo phqo) {
        //仅对app端使用
        if ("0".equals(phqo.getAtype())) {
            phqo.setAtype("");
        }

        QoHibernateStatelessResultAction<HealthActivitiesVO, HealthActivitiesQo> action = new QoHibernateStatelessResultAction(true, phqo, HealthActivitiesVO.class);
        action.setSql("SELECT {{t1.id as id ,t1.title as title ,t1.atype as atype ,t1.speakers as speakers ,t1.job_title as jobTitle ,t1.lecture_time as lectureTime ,t1.address as address ,t1.read_count as readCount ,t1.img as img," +
                "t1.contact as contact ,t1.contact_phone as contactPhone ,t1.fee as fee ,t1.start_time as startTime ,t1.create_user as createUser ,t1.create_dt as createDt ,t1.end_time as endTime ," +
                "t1.collect_count collectCount,t1.praise_count praiseCount,t1.share_count shareCount,substr(t1.content,1) as content," +
                "t1.disease_group_list as diseaseGroupList ,t1.disease_group_name as diseaseGroupName ,t1.person_group_list as personGroupList ,t1.status as status}} " +
                "from health_activities t1 where 1 = 1 and t1.status = 0");
        action.addCondition(" and t1.title like :title%");
        //由于web端的特殊需求 全部的话只穿一个名字却要查询主讲嘉宾或者联系人是传入参数名字的人
        if ("4".equals(phqo.getAtype())) {
            phqo.setAtype("");
            if (CommonUtils.isNotEmpty(phqo.getContact())) {
                action.addCondition(" and ( t1.speakers like :%contact%");
                action.addCondition(" or t1.contact like :%contact% )");
            }
        } else {
            action.addCondition(" and t1.atype= :atype");
            action.addCondition(" and t1.speakers like :%speakers%");
            action.addCondition(" and t1.contact like :%contact%");
        }
        if (CommonUtils.isNotEmpty(phqo.getStartTime())) {
            action.addCondition(" and t1.start_time >= :startTime");
        }
        if (CommonUtils.isNotEmpty(phqo.getEndTime())) {
            action.addCondition(" and t1.end_time <= :endTime");
        }
        //新的排序实现
        String order = "";
        if (CommonUtils.isNotEmpty(phqo.getOrderBy())) {
            String[] str = phqo.getOrderBy().split(",");
            order = " order by " + str[0] + " " + str[1];
        }
        if (CommonUtils.isNotEmpty(order)) {
            action.addOrder(order);
        } else {
            //原排序规则
            if (CommonUtils.isNotEmpty(phqo.getOrderbyclause()) && "startTime".equals(phqo.getOrderbyclause())) {
                action.addSql("order by t1.start_time desc");
            } else {
                action.addSql("order by t1.create_dt desc");
            }
        }


        HibernateSessionTemplate.instance().execute(action);
        //
        PageInfo<HealthActivitiesVO> pageInfo = action.getResultPage();
        //放入新的对象内
        HealthActivitiesAppVO paav = new HealthActivitiesAppVO();

        //总条数
        paav.setTotal(pageInfo.getTotal());
        paav.setPageSize(pageInfo.getPageSize());
        paav.setPageNo(pageInfo.getPageNum());
        paav.setList(pageInfo.getList());
        return paav;
    }

    /**
     * 获取用户的收藏记录
     *
     * @param qo
     * @return
     */
    @Deprecated
    public HealthActivitiesAppVO getUserMarkInfo(HealthActivitiesQo qo) {
        QoHibernateStatelessResultAction<HealthActivitiesVO, HealthActivitiesQo> action = new QoHibernateStatelessResultAction(true, qo, HealthActivitiesVO.class);
        action.setSql("SELECT {{b.id,b.title,b.atype,b.speakers,b.job_title,b.lecture_time,b.address,b.read_count,b.img,b.contact,b.contact_phone,b.fee,b.start_time,b.create_user,b.create_dt,b.end_time,b.collect_count,b.praise_count,b.share_count,substr(b.content,1) as content,b.people_classify_ids,b.status}} from health_activities b LEFT JOIN pcn_cms_action a ON a.business_obj_id = b.id where a.action='mark' and a.business_type='activity' ");
        action.addCondition("  and a.uid=:uid ");
        action.addCondition(" and b.atype =:atype");
        action.addSql(" ORDER BY b.create_dt desc");
        HibernateSessionTemplate.instance().execute(action);
        //
        PageInfo<HealthActivitiesVO> pageInfo = action.getResultPage();
        //放入新的对象内
        HealthActivitiesAppVO paav = new HealthActivitiesAppVO();

        //总条数
        paav.setTotal(pageInfo.getTotal());
        paav.setPageSize(pageInfo.getPageSize());
        paav.setPageNo(pageInfo.getPageNum());
        paav.setList(pageInfo.getList());
        return paav;
    }

    /**
     * 获取健康活动列表
     */
    public SimplePageInfo<HealthActivities> getActivitiesPage(HealthActivitiesListQo qo) {
        QoHibernateStatelessResultAction<HealthActivities, HealthActivitiesListQo> action
                = new QoHibernateStatelessResultAction<>(true, qo, HealthActivities.class);
        String sql = " SELECT {{" +
                "*" +
                "}} " +
                " FROM health_activities" +
                " WHERE 1=1";
        action.setSql(sql);
        action.addCondition(" AND id in (:ids) ");
        action.addCondition(" AND atype = (:atype) ");
//        if (qo.isDesc()) {
//            action.addOrder(" ORDER BY release_time DESC");
//        }

        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();
    }


    /**
     * 更新阅读量
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set readCount=readCount+1 where id=:id")
    public abstract void updateReadCount(@DAOParam("id") Integer id);

    /**
     * 维护阅读量
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set readCount=num where id=:id")
    public abstract void updateReadCountEdit(@DAOParam("id") Integer id, @DAOParam("num") Integer num);

    /**
     * 更新收藏数
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set collectCount=collectCount+1 where id=:id")
    public abstract void updateCollectCount(@DAOParam("id") Integer id);

    /**
     * 收藏减1
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set collectCount=collectCount-1 where id=:id")
    public abstract void updateCollectCountRedice(@DAOParam("id") Integer id);

    /**
     * 更新点赞
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set praiseCount=praiseCount+1 where id=:id")
    public abstract void updatePraiseCount(@DAOParam("id") Integer id);

    /**
     * 点赞减1
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set praiseCount=praiseCount-1 where id=:id")
    public abstract void updatePraiseCountRedice(@DAOParam("id") Integer id);

    /**
     * 更新删除状态
     *
     * @param status
     */
    @DAOMethod(sql = "update HealthActivities set status=:status where id=:id")
    public abstract void updateStatus(@DAOParam("status") Byte status, @DAOParam("id") Integer id);

    /**
     * 更新分享
     *
     * @param id
     */
    @DAOMethod(sql = "update HealthActivities set shareCount=shareCount+1 where id=:id")
    public abstract void updateShareCount(@DAOParam("id") Integer id);

    public void updateById(final HealthActivities pha) {
        HibernateStatelessResultAction action = new AbstractHibernateStatelessResultAction() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                Query query = ss.createQuery("update HealthActivities p set p.title=:title,p.img=:img,p.address=:address,p.diseaseGroupList=:diseaseGroupList,p.diseaseGroupName=:diseaseGroupName,p.personGroupList=:personGroupList,p.personGroupName=:personGroupName,p.startTime=:startTime,p.endTime=:endTime,p.atype=:atype,p.contact=:contact,p.contactPhone=:contactPhone,p.fee=:fee,p.content=:content,p.lastModifyUser=:lastModifyUser,p.lastModifyDt=:lastModifyDt where p.id=:id");
                query.setParameter("title", pha.getTitle());
                query.setParameter("img", pha.getImg());
                query.setParameter("address", pha.getAddress());
                query.setParameter("diseaseGroupList", pha.getDiseaseGroupList());
                query.setParameter("diseaseGroupName", pha.getDiseaseGroupName());
                query.setParameter("personGroupList", pha.getPersonGroupList());
                query.setParameter("personGroupName", pha.getPersonGroupName());
                query.setParameter("startTime", pha.getStartTime());
                query.setParameter("endTime", pha.getEndTime());
                query.setParameter("atype", pha.getAtype());
                query.setParameter("contact", pha.getContact());
                query.setParameter("contactPhone", pha.getContactPhone());
                query.setParameter("fee", pha.getFee());
                query.setParameter("content", pha.getContent());
                query.setParameter("id", pha.getId());
                query.setParameter("lastModifyUser", pha.getLastModifyUser());
                query.setParameter("lastModifyDt", pha.getLastModifyDt());
                query.executeUpdate();
            }
        };
        HibernateSessionTemplate.instance().execute(action);
    }

    /**
     * 查询出发送消息的用户id集合
     *
     * @param list
     * @return
     */
    public List<String> getUserIdlist(final List list) {
        HibernateStatelessResultAction<List<String>> action = new AbstractHibernateStatelessResultAction<List<String>>() {
            @Override
            public void execute(StatelessSession ss) throws Exception {
                StringBuffer sql = new StringBuffer();
                sql.append("select m.id_or_no from mpi_identity m left JOIN pcn_sign p on m.mpi_id = p.mpi_id where m.id_type= 01 and m.mpi_domain = 'hcn' " +
                        "and p.person_group in (:list)");
                sql.append("GROUP BY m.id_or_no");
                Query query = ss.createSQLQuery(sql.toString());
                query.setParameterList("list", list);
                List<String> resultList = (List<String>) query.list();
                setResult(resultList);
            }
        };
        HibernateSessionTemplate.instance().execute(action);
        List<String> list1 = action.getResult();
        return list1;
    }

}